'use strict';
const Controller = require('egg').Controller;
module.exports = app => {
  let mongo = app.mongo;
  let Mock = require('mockjs');
  return class SmsController extends Controller {
    async addSms() {
      let ctx = this.ctx;
      let {
        phone
      } = {
        ...ctx.query,
        ...ctx.request.body
      }
      const params = Mock.mock({
        phone,
        "smsCode|1000-9999": 1000,
        createTime: Date.now()
      })
      if (!phone) {
        ctx.body = {
          code: 1,
          msg: '缺少手机号码'
        }
        return false;
      }
      let reg = /^1[3456789]\d{9}$/;
      if (!reg.test(phone)) {
        ctx.body = {
          code: 1,
          msg: "请输入正确的手机号码"
        }
        return false;
      }
      // 结果集
      const resultSet = await mongo.insertOne('sms', {
        doc: params
      })
      if (resultSet.result.n > 0) {
        this.ctx.body = {
          ...params,
          code: 0,
          msg: '验证码生成成功'
        };
      } else {
        this.ctx.body = {
          code: 1,
          msg: '验证码生成失败'
        }
      }
    }

    async querySms() {
      const {
        smsCode,
        username
      } = {
        ...this.ctx.query,
        ...this.ctx.request.body
      }
      const resultSet = await mongo.find('sms', {
        query: {
          phone: username,
          smsCode: Number(smsCode)
        }
      });
      if (resultSet.length > 0) {
        const date = Date.now();
        let disTime = date - resultSet[0].createTime;
        // 120秒有效期
        if (disTime < 2 * 60 * 1000) {
          this.ctx.body = {
            code: 0,
            msg: '验证码正确'
          }
        } else {
          this.ctx.body = {
            code: 1,
            msg: '验证码已过期'
          }
        }
        return false;
      }
      this.ctx.body = {
        code: 1,
        msg: '验证码不正确'
      }

    }

    // 分页查询
    async queryByPage() {
      let {
        page = 1, limit = 10
      } = {
        ...this.ctx.query,
        ...this.ctx.request.body
      }
      // 查询创建时间小于2分钟的
      let now = Date.now();
      const resultSet = await mongo.find('sms', {
        query: {
          createTime: {
            $gt: now - 120000
          },
        },
        // limit:20,
        sort: {
          createTime: -1
        }
      });
      this.ctx.body = {
        code: 0,
        msg: 'success',
        list: resultSet
      }
    }

    async queryAll() {
      const resultSet = await mongo.find('sms');
      this.ctx.body = {
        code: 0,
        msg: 'success',
        list: resultSet
      }
    }
  }
}